﻿<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no" />
    
    <script src="../js/json2.js"></script>
    <script src="../js/jquery.js"></script>
    <title>停车场分布图</title>
    <link type="text/css" href="../css/demo.Default.css" rel="stylesheet" />
    <link type="text/css" href="../css/sous.css" rel="stylesheet" />
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=1c69b4a7bc3ff8773bcb6fa31605bb1c"></script>
</head>
<body>
    <input type="hidden" id="hilat" /><input type="hidden" id="hilng" style="margin:0px" />
    <div class="container -shadow-card index-widget-searchbox styleguide -lighter">
        <div class="input-group ">
            <div class="input-text -brand">
                <div class="ui-suggestion-mask">
                    <input name="wd" type="text" class="se-input-poi" id="se-input-poi" placeholder="根据位置搜索周边停车场" autocomplete="off"/>
                </div>
            </div>
            <button type="submit" class="btn -brand" id="se-btn" style="width:60px" onclick="placeSearch();">搜索</button>
        </div>
    </div>
    <div id="iCenter"></div>
</body>
</html>

<script  type="text/javascript">
    var mapObj, cluster, geolocation, circle, marker;
    var markers = new Array();
    //$.ajaxSetup({
    //    async: false
    //});
    $(document).ready(function () {
        mapInit();
        
        var agent = window.navigator.userAgent;
        if (agent.indexOf("Android") >= 0 || agent.indexOf('Linux') >= 0) {
            
            var _location = getQueryString("_location");
            if (_location) {
                var lon0 = _location.split(',')[0];
                var lat0 = _location.split(',')[1];
                addCircle(lon0, lat0);
                addMarker(lon0, lat0);
            }
        }else {
            getCurrentPosition();
        }
    });

    //添加点标记
    function addMarker(LngLatX, LngLatY) {
        marker = new AMap.Marker({
            icon: "http://webapi.amap.com/images/marker_sprite.png",
            position: new AMap.LngLat(LngLatX, LngLatY)
        });

        marker.setMap(mapObj);  //在地图上添加点
        mapObj.setFitView(); //调整到合理视野
    }

    function getQueryString(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }

    //添加圆覆盖物
    function addCircle(lat, lon) {
        circle = new AMap.Circle({
            center: new AMap.LngLat(lat, lon),// 圆心位置
            radius: 50, //半径
            strokeColor: "#F33", //线颜色
            strokeOpacity: 1, //线透明度
            strokeWeight: 3, //线粗细度
            fillColor: "#ee2200", //填充颜色
            fillOpacity: 0.35//填充透明度
        });
        circle.setMap(mapObj);

    }

    //根据关键字查询
    function placeSearch() {
        var searchValue = $("#se-input-poi").val();
        if (searchValue) {
            var MSearch;
            mapObj.plugin(["AMap.PlaceSearch"], function () {
                MSearch = new AMap.PlaceSearch({ //构造地点查询类 
                    pageSize: 5,
                    pageIndex: 1,
                    city: "010" //城市，北京 
                });
                AMap.event.addListener(MSearch, "complete", keywordSearch_CallBack);//返回地点查询结果 

                MSearch.search(searchValue); //关键字查询 
            });
        }
    }
    //回调函数 
    function keywordSearch_CallBack(data) {
        var resultStr = "";
        var poiArr = data.poiList.pois;
        var resultCount = poiArr.length;
        for (var i = 0; i < resultCount; i++) {
            resultStr += "<div id='divid" + (i + 1) + "' onmouseover='openMarkerTipById1(" + i + ",this)' onmouseout='onmouseout_MarkerStyle(" + (i + 1) + ",this)' style=\"font-size: 12px;cursor:pointer;padding:0px 0 4px 2px; border-bottom:1px solid #C1FFC1;\"><table><tr><td><img src=\"http://webapi.amap.com/images/" + (i + 1) + ".png\"></td>" + "<td><h3><font color=\"#00a6ac\">名称: " + poiArr[i].name + "</font></h3>";
            resultStr += TipContents(poiArr[i].type, poiArr[i].address, poiArr[i].tel) + "</td></tr></table></div>";
            addmarker(i, poiArr[i]);
        }
        mapObj.setFitView();
    }

    //添加marker&infowindow     
    function addmarker(i, d) {
        var lngX = d.location.getLng();
        var latY = d.location.getLat();
        var markerOption = {
            map: mapObj,
            icon: "http://webapi.amap.com/images/" + (i + 1) + ".png",
            position: new AMap.LngLat(lngX, latY)
        };
        var mar = new AMap.Marker(markerOption);
        //marker.push(new AMap.LngLat(lngX, latY));

        var infoWindow = new AMap.InfoWindow({
            content: "<h3><font color=\"#00a6ac\">  " + (i + 1) + ". " + d.name + "</font></h3>" + TipContents(d.type, d.address, d.tel),
            size: new AMap.Size(290, 0),
            autoMove: true,
            offset: new AMap.Pixel(0, -30)
        });
        //windowsArr.push(infoWindow);
        var aa = function (e) { infoWindow.open(mapObj, mar.getPosition()); };
        AMap.event.addListener(mar, "click", aa);
    }

    function TipContents(type, address, tel) {  //窗体内容 
        if (type == "" || type == "undefined" || type == null || type == " undefined" || typeof type == "undefined") {
            type = "暂无";
        }
        if (address == "" || address == "undefined" || address == null || address == " undefined" || typeof address == "undefined") {
            address = "暂无";
        }
        if (tel == "" || tel == "undefined" || tel == null || tel == " undefined" || typeof address == "tel") {
            tel = "暂无";
        }
        var str = "  地址：" + address + "<br />  电话：" + tel + " <br />  类型：" + type;
        return str;
    }

    function WDContents(adress, cost, openingTime, _location, name, count) {
        var lon = _location.split(',')[0];
        var lat = _location.split(',')[1];
        var mapurl = "http://mo.amap.com/?q=" + lat + "," + lon + "&name=" + name + "&dev=0";
        var str = "  价格：" + cost + "(小型车)  <br />  营业时间：" + openingTime + "<br />  备案车位数：" + count + "<br />地址：" + adress + "<br /><a class=\"uk-button-link\" href=\" " + mapurl + "\">到这儿去</a>";

        return str;
    }

    /*
     *地图初始化&向地图加载网点
     */
    function mapInit() {
        mapObj = new AMap.Map("iCenter", {
            center: new AMap.LngLat(116.397428, 39.90923), //地图中心点
            level: 16  //地图显示的比例尺级别
        });

        queryStation();

        var agent = window.navigator.userAgent;
        if (agent.indexOf("Android") < 0 && agent.indexOf('Linux') < 0) {
            addlocation(mapObj);
        }
    }

    /*
   *添加站点信息
   */
    function queryStation() {
        // &filter=type:写字楼&limit=50&page=1&key=<用户key>     //搜索存储在云图数据表中的北京市的写字楼，返回第一页数据
        $.ajax({
            type: "GET",
            async: true,
            url: "http://yuntuapi.amap.com/datasearch/local?tableid=53e8b75ce4b08f92c0ffa6f2&city=北京市&keywords= &key=1c69b4a7bc3ff8773bcb6fa31605bb1c&limit=100&page=1",
            dataType: "jsonp",//返回json格式的数据
            //jsonp: "callback",//传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
            //jsonpCallback: "callback",//自定义的jsonp回调函数名，默认未jquery自动生成的随机函数名，也可以写“?”jquery会自动处理
            success: function (data) {
                if (data) {
                    add(data);
                }
                addCluster(0);
                var total = data.count;
                var pages = total / 100;
                var index = 1;
                while (index < pages) {
                    index = index + 1;
                    $.ajax({
                        type: "GET",
                        async: true,
                        url: "http://yuntuapi.amap.com/datasearch/local?tableid=53e8b75ce4b08f92c0ffa6f2&city=北京市&keywords= &key=1c69b4a7bc3ff8773bcb6fa31605bb1c&limit=100&page=" + index,
                        dataType: "jsonp",//返回json格式的数据
                        success: function (data) {
                            if (data) {
                                add(data);
                            }
                            addCluster(0);
                        }
                    });
                }
            }
        });
    }
    //<img src="../images/parking.png" />
    function add(data) {
        $.each(data.datas, function (i, n) {
            var lon = n._location.split(',')[0];
            var lat = n._location.split(',')[1];
            var markerPosition = new AMap.LngLat(lon, lat);
            var marker = new AMap.Marker({
                position: markerPosition, //基点位置
                icon: "../images/parking2.png",
                offset: { x: -8, y: -34 } //相对于基点的位置
            });
            //添加窗口信息
            var infoWindow = new AMap.InfoWindow({
                content: "<h3><font color=\"#00a6ac\">" + n._name + "</font></h3>" + WDContents(n._address, n.cost, n.openingTime, n._location, n._name, n.count),
                size: new AMap.Size(290, 0),
                autoMove: false,
                offset: new AMap.Pixel(0, -30)
            });
            //windowsArr.push(infoWindow);
            var aa = function (e) { infoWindow.open(mapObj, marker.getPosition()); };
            AMap.event.addListener(marker, "click", aa);
            markers.push(marker);
        });
    }

    /*
    *添加定位控件
    */
    function addlocation() {
        mapObj.plugin('AMap.Geolocation', function () {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                maximumAge: 0,           //定位结果缓存0毫秒，默认：0
                convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
                showButton: true,        //显示定位按钮，默认：true
                buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
                buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                showMarker: true,        //定位成功后在定位到的位置显示点标记，默认：true
                showCircle: true,        //定位成功后用圆圈表示定位精度范围，默认：true
                panToLocation: true,     //定位成功后将定位到的位置作为地图中心点，默认：true
                zoomToAccuracy: true      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            });
            mapObj.addControl(geolocation);
            AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
            AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        });
    }

    /*
     *添加点聚合显示
     *
     */
    function addCluster(tag) {
        if (cluster) {
            cluster.setMap(null);
        }

        mapObj.plugin(["AMap.MarkerClusterer"], function () {
            cluster = new AMap.MarkerClusterer(mapObj, markers);
        });
    }

    /*
     *获取当前位置信息
     */
    function getCurrentPosition() {
        geolocation.getCurrentPosition();
        mapObj.setFitView(); //调整到合理视野
    };
    /*
     *监控当前位置并获取当前位置信息
     */
    function watchPosition() {
        geolocation.watchPosition();
    }
    /*
     *解析定位结果
     */
    function onComplete(data) {
        var str = '<p>定位成功</p>';
        str += '<p>经度：' + data.position.getLng() + '</p>';
        str += '<p>纬度：' + data.position.getLat() + '</p>';
        str += '<p>精度：' + data.accuracy + ' 米</p>';
        str += '<p>是否经过偏移：' + (data.isConverted ? '是' : '否') + '</p>';
        //result.innerHTML = str;
    }
    /*
     *解析定位错误信息
     */
    function onError(data) {
        var str = '定位失败，';
        switch (data.info) {
            case 'PERMISSION_DENIED':
                str += '请打开定位服务';
                break;
            case 'POSITION_UNAVAILBLE':
                str += '无法获得当前位置';
                break;
            case 'TIMEOUT':
                str += '定位超时';
                break;
            default:
                str += '未知错误';
                break;
        }
        alert(str);
        //result.innerHTML = str;
    }
</script>

